<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace User\Validator;

use Laminas\I18n\Translator\Translator;
use Laminas\Validator\AbstractValidator;
use Laminas\Validator\StringLength;

class UserPasswordValidator extends AbstractValidator
{
    const ERROR_MES = 'errorMes';
    const PASSWORD_LENGTH = 'passwordLength';

    protected $messageTemplates = [];

    public function __construct($options = null)
    {
        $trans = new Translator();
        $this->messageTemplates = [
            self::ERROR_MES         => $trans->translate("必须包含字母、数字和特殊字符"),
            self::PASSWORD_LENGTH   => $trans->translate("密码至少为8位，且包含字母、数字、特殊字符")
        ];

        parent::__construct($options);
    }

    public function isValid($value)
    {
        $strLength = new StringLength(['min' => 8, 'max' => 20]);
        if (!$strLength->isValid($value)) {
            $this->error(self::PASSWORD_LENGTH);
            return false;
        }

        $search = '/^(?![A-Za-z]+$)(?![A-Z\d]+$)(?![A-Z\W]+$)(?![a-z\d]+$)(?![a-z\W]+$)(?![\d\W]+$)\S{8,20}$/';
        if (preg_match($search, $value)) return true;
        else {
            $this->error(self::ERROR_MES);
            return false;
        }
    }
}